package com.xca.znb.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.xca.znb.R;
import com.xca.znb.model.impl.SchoolEssayImpl;
import com.xca.znb.presenter.SchoolEssayPresenter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class SchoolEssayActivity extends AppCompatActivity {
    private SchoolEssayPresenter presenter ;
    private static final int PICK_IMAGE_REQUEST = 1;
    private ImageButton Back ;
    private Spinner publish_type ;
    private EditText firstTitle , secondTitle , inputText;
    private ImageView imgFirst ;
    private TextView publishBtn ;
    private String selectedItemText ;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.school_essay);
        Back = findViewById(R.id.school_essay_back) ;
        publish_type =(Spinner) findViewById(R.id.school_essay_publish_type);
        firstTitle = findViewById(R.id.essay_first_title) ;
        secondTitle = findViewById(R.id.essay_second_title) ;
        inputText = findViewById(R.id.essay_texts) ;
        imgFirst = findViewById(R.id.essay_img) ;
        publishBtn = findViewById(R.id.essay_publish_btn);
        Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        Intent intent = getIntent();
        int publishType = intent.getIntExtra("publish_type" ,0);
        publish_type.setSelection(publishType);

        SchoolEssayImpl schoolEssay = new SchoolEssayImpl(this);
        presenter = new SchoolEssayPresenter(schoolEssay);

        // 获取选中项的文本
         selectedItemText = publish_type.getSelectedItem().toString();
        // 获取选中项的位置索引
//        int selectedItemPosition = publish_type.getSelectedItemPosition();

        //获取图片路径
        imgFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
            }
        });
//        SharedPreferences sharedPreferences1 = getSharedPreferences("imgPath" , Context.MODE_PRIVATE);
//        String img = sharedPreferences1.getString("imagePath" , "");
//
//
//        //获取loginId ;
//        SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
//        String phone = sharedPreferences.getString("phone" , "");
//
//
//        publishBtn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                //获取主标题
//                String first_title = firstTitle.getText().toString();
//                //获取副标题
//                String second_title = secondTitle.getText().toString();
//                //获取输入文本
//                String input_text = inputText.getText().toString();
//
//                Uri uri = Uri.parse(img);
//                String imgPath = saveImageToAppFolder(uri);
//                Toast.makeText(SchoolEssayActivity.this, imgPath, Toast.LENGTH_SHORT).show();
//                //获取时间
//                LocalDateTime nowTime = LocalDateTime.now() ;
//                String dayTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//                boolean isAdd = presenter.addNews(selectedItemText , first_title , second_title , imgPath
//                        , input_text , phone , dayTime);
//                if (isAdd){
//                    Toast.makeText(SchoolEssayActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
//                    finish();
//                }else {
//                    Toast.makeText(SchoolEssayActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
//                }
//            }
//        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri selectedImageUri = data.getData();
            String imagePath = selectedImageUri.toString();
//            SharedPreferences sharedPreferences = getSharedPreferences("imgPath" , Context.MODE_PRIVATE);
//            SharedPreferences.Editor editor = sharedPreferences.edit() ;
//            editor.putString("imagePath" , imagePath);
//            editor.apply();
            Uri uri = Uri.parse(imagePath);
            imgFirst.setImageURI(uri);


            //获取loginId ;
            SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
            String phone = sharedPreferences.getString("phone" , "");
            publishBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String first_title = firstTitle.getText().toString().trim();
                    String second_title = secondTitle.getText().toString().trim();
                    String input_text = inputText.getText().toString().trim();
                    String imagePath = saveImageToAppFolder(uri);
                    //获取时间
                    LocalDateTime nowTime = LocalDateTime.now() ;
                    String dayTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    boolean isAdd = presenter.addNews(selectedItemText , first_title , second_title , imagePath
                            , input_text , phone , dayTime);
                    if (isAdd){
                        Toast.makeText(SchoolEssayActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }else {
                        Toast.makeText(SchoolEssayActivity.this, "发布失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    private String saveImageToAppFolder(Uri imageUri) {
        String savedImagePath = null;

        if (imageUri == null || imageUri.toString().isEmpty()) {
            Log.e("ImageSave", "Invalid image Uri provided");
            return null;
        }

        try {
            File dir_news = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (dir_news == null) {
                Log.e("ImageSave", "Failed to get app's private directory");
                return null;
            }

            if (!dir_news.exists() && !dir_news.mkdirs()) {
                Log.e("ImageSave", "Failed to create directories");
                return null;
            }

            // 确保文件名唯一，优化逻辑减少循环次数
            String imageNameBase = "image_";
            String imageNameExtension = ".jpg";
            long timestamp = System.currentTimeMillis();
            File file = new File(dir_news, imageNameBase + timestamp + imageNameExtension);
            int counter = 1;
            while (file.exists()) {
                file = new File(dir_news, imageNameBase + timestamp + "_" + counter++ + imageNameExtension);
            }

            try (InputStream inputStream = getContentResolver().openInputStream(imageUri);
                 FileOutputStream outputStream = new FileOutputStream(file)) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                savedImagePath = file.getAbsolutePath();
                Log.d("ImageSave", "Image saved successfully at: " + savedImagePath);
            }
        } catch (SecurityException se) {
            Log.e("ImageSave", "Security exception when accessing storage", se);
        } catch (FileNotFoundException fnfe) {
            Log.e("ImageSave", "Image file not found", fnfe);
        } catch (IOException ioe) {
            Log.e("ImageSave", "Error occurred during image saving", ioe);
        }

        return savedImagePath;
    }

}
